

import 'package:erp/Entity/SalesOrder.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/SalesOrderStore.dart';
import 'package:erp/global.dart';

void registerSalesOrderEvents(){
  globalBus.subscribe(Events.SALES_ORDER_SELECT_REQUEST, (bus, _) async {
    try {
      var data = await externalInterface.getAllSalesOrders(AccountStore.signInResult.token);
      SalesOrderStore.orders = data;
      bus.publish(Events.SALES_ORDER_SELECT_SUCCESS, data);
    }
    catch (exception){
      bus.publish(Events.SALES_ORDER_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<SalesOrder>(Events.SALES_ORDER_DETAIL_SELECT_REQUEST, (bus, order) async {
    try {
      var data = await externalInterface.getProductGroupsInSalesOrder(AccountStore.signInResult.token, order);
      SalesOrderStore.orders.singleWhere((item) => item.orderNumber == order.orderNumber).products = data;
      bus.publish(Events.SALES_ORDER_DETAIL_SELECT_SUCCESS, data);
    }
    catch (exception){
      bus.publish(Events.SALES_ORDER_DETAIL_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<SalesOrder>(Events.SALES_ORDER_INSERT_REQUEST, (bus, order) async {
//    try {
      var data = await externalInterface.addSalesOrder(AccountStore.signInResult.token, order);
      SalesOrderStore.orders.add(data);
      bus.publish(Events.SALES_ORDER_INSERT_SUCCESS, data);
//    }
//    catch (exception) {
//      bus.publish(Events.SALES_ORDER_INSERT_ERROR, exception);
//    }
  });
}
